// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
const dbUser = db.collection('user')
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()

    //注册新用户 需要传一个event.userInfo
    if (event.action === 'newUser') {
        const user = await dbUser.where({
            openid: event.userInfo.openid
        }).get()
        if(user['data'].length == 0){
            dbUser.add({
                data:{
                    avatarUrl: event.userInfo.avatarUrl,
                    credit: 0,
                    nickName: event.userInfo.nickName,
                    taskListPublish: [],
                    taskListReceive: [],
                    openid: event.userInfo.openid
                }
            })
            return true
        }else{
            return false
        }
    } else {
        //增加用户积分
        if (event.action === 'addCredit' && event.num > 0) {
            return await dbUser.where({
                openid: event.openid
            }).update({
                data:{
                    credit: _.inc(event.num)
                }
            })
        }
        //扣除用户积分
        else if (event.action === 'subCredit' && event.num > 0) {
            return await dbUser.where({
                openid: event.openid
            }).update({
                data:{
                    credit: _.inc(-event.num)
                }
            })
        }
        //增加发布任务ID
        else if (event.action === 'addTaskPID' && event._id) {
            return await dbUser.where({
                openid: event.openid
            }).update({
                data:{
                    taskListPublish: _.push([event._id])
                }
            })
        }
        //移除发布任务ID
        else if (event.action === 'removeTaskPID' && event._id) {
            return await dbUser.where({
                openid: event.openid
            }).update({
                data:{
                    taskListPublish: _.pull(event._id)
                }
            })
        }
        //增加接收任务ID
        else if (event.action === 'addTaskRID' && event._id) {
            return await dbUser.where({
                openid: event.openid
            }).update({
                data:{
                    taskListReceive: _.push([event._id])
                }
            })
        }
        //移除接收任务ID
        else if (event.action === 'removeTaskRID' && event._id) {
            return await dbUser.where({
                openid: event.openid
            }).update({
                data:{
                    taskListReceive: _.pull(event._id)
                }
            })
        }
    }
}